package org.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
//UDP接收数据  先运行接收端  再运行发送端
public class GetMassage {
    public static void main(String[] args) throws IOException {

        //创建一个DatagramSocket对象 从端口10086接收数据
        DatagramSocket ds = new DatagramSocket(10086);


        //创建一个DatagramPacket对象 用于接收数据
        byte[] bytes = new byte[1024];  //接收数据的字节数组
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        //接收数据
        ds.receive(dp);

        //解析数据
        byte[] data = dp.getData();
        int len=dp.getLength();
        InetAddress address = dp.getAddress();
        String ip = address.getHostAddress();
        int port = dp.getPort();
        String str = new String(data, 0, len);//将字节数组转换为字符串
        System.out.println("客户端"+ip+":"+port+"说："+str);

        //关闭资源
        ds.close();

    }
}